//
//  HomeTableViewController.swift
//  晓庄微博
//
//  Created by Maxwell on 10/15/18.
//  Copyright © 2018 Maxwell. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class HomeTableViewController: BaseTableViewController{

    let myGroup = DispatchGroup()
    
    var weiboHomeDatas = [WeiboData]()
    var acc_token = ""
    
    let home_timeline_url = "https://api.weibo.com/2/statuses/home_timeline.json"
    let cellID = "weiboCell"
    
    override func loadView() {
        super.loadView()
        if self.userLogin{
            if let token = self.access_token{
                print("token = \(token) ")
                self.acc_token = token
                self.accessUserHomepage()
            }
        }
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = (tableView.dequeueReusableCell(withIdentifier:cellID, for: indexPath)) as UITableViewCell
        cell.textLabel?.text = weiboHomeDatas[indexPath.row].text
        cell.textLabel?.numberOfLines = 0
        return cell
    }
   
    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return weiboHomeDatas.count
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        guestView?.setupInfo(isHome: true, imageName: "visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜")
        
        if self.userLogin{
            myGroup.notify(queue: DispatchQueue.main, execute: {
                self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: self.cellID)
                self.tableView.reloadData()
            })
            
        }
        
    }
    
    func accessUserHomepage(){
        myGroup.enter()
        let canshu = ["access_token":"\(acc_token)"]
        Alamofire.request(home_timeline_url, method: .get, parameters: canshu, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            switch response.result.isSuccess {
            case true:
                if let value = response.result.value {
                    let json = JSON(value)
//                    let weibo1 = json["statuses"][0]
//                    print("成功地获取用户首页，用户首页的数据是：\(weibo1)")
                    //1.存储到模型
                    self.weiboHomeDatas = self.saveWeiboHome(jsondata:json)
                }
            case false:
                print(response.result.error!)
            }
           self.myGroup.leave()
        }
        
    }
    
    func saveWeiboHome(jsondata:JSON) -> [WeiboData]{
        var weiboshouye = [WeiboData]()
        for i in 0..<jsondata["statuses"].count {
            let weibo1 = WeiboData(jsonData: jsondata["statuses"][i])
            weiboshouye.append(weibo1)
        }
        return weiboshouye
    }
    
 
}
